pipeline {
    agent any
    
    parameters {
        choice(
            name: 'DEPLOY_ACTION',
            choices: ['BUILD_AND_DEPLOY', 'BUILD_ONLY', 'DEPLOY_ONLY'],
            description: '选择执行动作'
        )
        booleanParam(
            name: 'SKIP_HEALTH_CHECK',
            defaultValue: false,
            description: '跳过健康检查'
        )
        booleanParam(
            name: 'BACKUP_OLD_VERSION',
            defaultValue: true,
            description: '备份旧版本'
        )
    }
    
    environment {
        // Git 配置
        GIT_REPO = 'http://112.11.119.99:10068/dasapp/dasapp-commhub'
        GIT_BRANCH = 'beta'
        GIT_TOKEN = 'glpat-fjzYua8p_aCUgishdMTA'
        
        // 项目配置
        PROJECT_DIR = './cmd/admin-liunx'
        BINARY_NAME = 'dasapp-commhub-jenkins'
        BUILD_DIR = './bin'
        
        // 服务器配置
        TARGET_SERVER = '10.2.106.51'
        SSH_PORT = '65434'
        SSH_USER = 'root'
        
        // 部署配置
        DEPLOY_DIR = '/data/dasapp-commhub/jenkins'
        BIN_DIR = '/data/dasapp-commhub/jenkins/bin'
        CONFIG_DIR = '/data/dasapp-commhub/jenkins/deployment'
        
        // 服务配置
        SERVICE_START_CMD = '/data/dasapp-commhub/jenkins/bin/dasapp-commhub-jenkins -dir /data/dasapp-commhub/jenkins'
        SERVICE_STOP_CMD = 'pkill dasapp-commhub-jenkins'
        HEALTH_CHECK_CMD = 'ps aux | grep dasapp-commhub-jenkins | grep -v grep'
    }
    
    stages {
        stage('初始化') {
            steps {
                script {
                    echo "=== DasApp CommHub 部署流水线 ==="
                    echo "执行动作: ${params.DEPLOY_ACTION}"
                    echo "跳过健康检查: ${params.SKIP_HEALTH_CHECK}"
                    echo "备份旧版本: ${params.BACKUP_OLD_VERSION}"
                    echo "Git 仓库: ${env.GIT_REPO}"
                    echo "目标分支: ${env.GIT_BRANCH}"
                    echo "目标服务器: ${env.TARGET_SERVER}:${env.SSH_PORT}"
                    echo "部署目录: ${env.DEPLOY_DIR}"
                    echo "二进制文件: ${env.BINARY_NAME}"
                    echo "流水线开始执行..."
                }
            }
        }
        
        stage('代码检出') {
            when {
                expression { params.DEPLOY_ACTION != 'DEPLOY_ONLY' }
            }
            steps {
                script {
                    echo "开始代码检出..."
                    
                    // 清理工作空间
                    sh '''
                        echo "清理工作空间..."
                        rm -rf * || true
                        rm -rf .git || true
                    '''
                    
                    // 克隆代码
                    sh """
                        echo "克隆代码仓库..."
                        git clone -b ${env.GIT_BRANCH} http://oauth2:${env.GIT_TOKEN}@${env.GIT_REPO.replace('http://', '')} ./
                    """
                    
                    // 验证代码
                    sh '''
                        echo "验证代码结构..."
                        ls -la
                        if [ -d "${PROJECT_DIR}" ]; then
                            echo "✅ 项目目录存在"
                            ls -la ${PROJECT_DIR}
                        else
                            echo "❌ 项目目录不存在"
                            exit 1
                        fi
                    '''
                    
                    echo "代码检出完成"
                }
            }
        }
        
        stage('构建应用') {
            when {
                expression { params.DEPLOY_ACTION != 'DEPLOY_ONLY' }
            }
            steps {
                script {
                    echo "开始构建 Go 应用..."
                    
                    // 设置 Go 环境
                    sh '''
                        echo "设置 Go 环境..."
                        export PATH=/usr/local/go/bin:$PATH
                        go version
                        echo "Go 环境设置完成"
                    '''
                    
                    // 下载依赖
                    sh '''
                        echo "下载项目依赖..."
                        export PATH=/usr/local/go/bin:$PATH
                        cd ${PROJECT_DIR}
                        go mod download
                        go mod tidy
                        echo "依赖下载完成"
                    '''
                    
                    // 编译二进制文件
                    sh '''
                        echo "编译二进制文件..."
                        export PATH=/usr/local/go/bin:$PATH
                        cd ${PROJECT_DIR}
                        
                        # 创建输出目录
                        mkdir -p ../../bin
                        
                        # 编译 (禁用CGO，静态编译)
                        CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \\
                            -ldflags="-w -s" \\
                            -o ../../bin/${BINARY_NAME} .
                        
                        echo "编译完成"
                    '''
                    
                    // 验证构建产物
                    sh '''
                        echo "验证构建产物..."
                        ls -la ${BUILD_DIR}/
                        
                        if [ -f "${BUILD_DIR}/${BINARY_NAME}" ]; then
                            echo "✅ 二进制文件存在"
                            file ${BUILD_DIR}/${BINARY_NAME}
                            chmod +x ${BUILD_DIR}/${BINARY_NAME}
                            echo "文件大小: $(ls -lh ${BUILD_DIR}/${BINARY_NAME} | awk '{print $5}')"
                        else
                            echo "❌ 二进制文件不存在"
                            exit 1
                        fi
                    '''
                    
                    echo "应用构建完成"
                }
            }
        }
        
        stage('部署确认') {
            when {
                expression { params.DEPLOY_ACTION != 'BUILD_ONLY' }
            }
            steps {
                script {
                    echo "=== 部署确认 ==="
                    echo "即将部署到测试环境："
                    echo "服务器: ${env.TARGET_SERVER}:${env.SSH_PORT}"
                    echo "部署路径: ${env.DEPLOY_DIR}"
                    echo "二进制文件: ${env.BINARY_NAME}"
                    echo "备份旧版本: ${params.BACKUP_OLD_VERSION}"
                    
                    // 手动确认部署
                    input message: '确认部署到测试环境？',
                          ok: '确认部署',
                          submitterParameter: 'DEPLOYER'
                    
                    echo "部署确认完成，执行者: ${env.DEPLOYER}"
                }
            }
        }
        
        stage('停止旧服务') {
            when {
                expression { params.DEPLOY_ACTION != 'BUILD_ONLY' }
            }
            steps {
                script {
                    echo "停止旧服务..."
                    
                    sh '''
                        echo "检查并停止旧服务..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            echo "当前运行的服务:"
                            ps aux | grep ${BINARY_NAME} | grep -v grep || echo "没有运行的服务"
                            
                            echo "停止服务..."
                            ${SERVICE_STOP_CMD} || echo "没有需要停止的服务"
                            
                            echo "等待服务停止..."
                            sleep 3
                            
                            echo "确认服务已停止:"
                            ps aux | grep ${BINARY_NAME} | grep -v grep || echo "服务已停止"
                        '''
                    '''
                    
                    echo "旧服务停止完成"
                }
            }
        }
        
        stage('部署二进制') {
            when {
                expression { params.DEPLOY_ACTION != 'BUILD_ONLY' }
            }
            steps {
                script {
                    echo "开始部署二进制文件..."
                    
                    // 创建部署目录
                    sh '''
                        echo "创建部署目录..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            mkdir -p ${DEPLOY_DIR}
                            mkdir -p ${BIN_DIR}
                            mkdir -p ${CONFIG_DIR}
                            echo "部署目录创建完成"
                        '''
                    '''
                    
                    // 备份旧版本
                    script {
                        if (params.BACKUP_OLD_VERSION) {
                            echo "备份旧版本..."
                            sh '''
                                ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                                    if [ -f ${BIN_DIR}/${BINARY_NAME} ]; then
                                        BACKUP_NAME="${BINARY_NAME}.backup.$(date +%Y%m%d_%H%M%S)"
                                        echo "备份文件: $BACKUP_NAME"
                                        cp ${BIN_DIR}/${BINARY_NAME} ${BIN_DIR}/$BACKUP_NAME
                                        echo "✅ 旧版本备份完成"
                                    else
                                        echo "没有旧版本需要备份"
                                    fi
                                '''
                            '''
                        } else {
                            echo "跳过备份旧版本"
                        }
                    }
                    
                    // 上传新版本
                    sh '''
                        echo "上传新版本..."
                        scp -o StrictHostKeyChecking=no -P ${SSH_PORT} \\
                            ${BUILD_DIR}/${BINARY_NAME} \\
                            ${SSH_USER}@${TARGET_SERVER}:${BIN_DIR}/
                        echo "新版本上传完成"
                    '''
                    
                    // 设置文件权限
                    sh '''
                        echo "设置文件权限..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            chmod +x ${BIN_DIR}/${BINARY_NAME}
                            chown ${SSH_USER}:${SSH_USER} ${BIN_DIR}/${BINARY_NAME}
                            
                            echo "文件权限设置完成"
                            ls -la ${BIN_DIR}/${BINARY_NAME}
                        '''
                    '''
                    
                    echo "二进制文件部署完成"
                }
            }
        }
        
        stage('启动服务') {
            when {
                expression { params.DEPLOY_ACTION != 'BUILD_ONLY' }
            }
            steps {
                script {
                    echo "启动服务..."
                    
                    // 启动服务
                    sh '''
                        echo "启动新服务..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            cd ${DEPLOY_DIR}
                            echo "当前目录: $(pwd)"
                            
                            # 使用 nohup 在后台启动服务
                            nohup ${SERVICE_START_CMD} > /dev/null 2>&1 &
                            
                            echo "服务启动命令已执行"
                            echo "等待服务启动..."
                            sleep 5
                        '''
                    '''
                    
                    echo "服务启动完成"
                }
            }
        }
        
        stage('健康检查') {
            when {
                expression { 
                    params.DEPLOY_ACTION != 'BUILD_ONLY' && !params.SKIP_HEALTH_CHECK 
                }
            }
            steps {
                script {
                    echo "开始健康检查..."
                    
                    // 第一次检查
                    sh '''
                        echo "第一次健康检查..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            echo "检查服务进程..."
                            ${HEALTH_CHECK_CMD}
                        '''
                    '''
                    
                    // 等待服务完全启动
                    echo "等待服务完全启动..."
                    sleep 10
                    
                    // 最终健康检查
                    sh '''
                        echo "最终健康检查..."
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            if ${HEALTH_CHECK_CMD}; then
                                echo "✅ 服务运行正常"
                                echo "服务详情:"
                                ${HEALTH_CHECK_CMD}
                            else
                                echo "❌ 服务未正常运行"
                                echo "请检查服务日志"
                                exit 1
                            fi
                        '''
                    '''
                    
                    echo "健康检查通过"
                }
            }
        }
        
        stage('部署总结') {
            when {
                expression { params.DEPLOY_ACTION != 'BUILD_ONLY' }
            }
            steps {
                script {
                    echo "=== 部署总结 ==="
                    echo "✅ 部署完成"
                    echo "服务器: ${env.TARGET_SERVER}:${env.SSH_PORT}"
                    echo "部署路径: ${env.DEPLOY_DIR}"
                    echo "二进制文件: ${env.BIN_DIR}/${env.BINARY_NAME}"
                    echo "启动命令: ${env.SERVICE_START_CMD}"
                    echo "健康检查: ${env.HEALTH_CHECK_CMD}"
                    
                    // 显示服务状态
                    sh '''
                        echo "当前服务状态:"
                        ssh -o StrictHostKeyChecking=no -p ${SSH_PORT} ${SSH_USER}@${TARGET_SERVER} '''
                            ${HEALTH_CHECK_CMD} || echo "服务未运行"
                        '''
                    '''
                }
            }
        }
    }
    
    post {
        always {
            script {
                echo "=== 流水线执行完成 ==="
                echo "执行结果: ${currentBuild.currentResult}"
                echo "执行时间: ${currentBuild.durationString}"
                echo "执行者: ${env.BUILD_USER_ID ?: 'Unknown'}"
                echo "执行动作: ${params.DEPLOY_ACTION}"
            }
        }
        
        success {
            script {
                echo "🎉 流水线执行成功！"
                
                if (params.DEPLOY_ACTION == 'BUILD_AND_DEPLOY') {
                    echo "✅ 应用已成功部署到测试环境"
                    echo "🌐 服务器: ${env.TARGET_SERVER}:${env.SSH_PORT}"
                    echo "📁 部署路径: ${env.DEPLOY_DIR}"
                    echo "🚀 服务已启动并通过健康检查"
                } else if (params.DEPLOY_ACTION == 'BUILD_ONLY') {
                    echo "✅ 应用构建成功"
                    echo "📦 二进制文件: ${env.BUILD_DIR}/${env.BINARY_NAME}"
                    echo "💡 提示: 使用 'BUILD_AND_DEPLOY' 选项来部署到服务器"
                } else if (params.DEPLOY_ACTION == 'DEPLOY_ONLY') {
                    echo "✅ 应用部署成功"
                    echo "🚀 服务已启动"
                }
            }
        }
        
        failure {
            script {
                echo "❌ 流水线执行失败！"
                echo "📋 失败阶段: ${env.STAGE_NAME ?: 'Unknown'}"
                echo "🔍 请检查上方的错误日志"
                echo "💡 常见问题排查:"
                echo "  1. 检查 Git 仓库访问权限"
                echo "  2. 检查 Go 环境和依赖"
                echo "  3. 检查 SSH 连接和权限"
                echo "  4. 检查服务器磁盘空间"
                echo "  5. 检查服务启动权限"
                
                // 在失败时显示一些调试信息
                script {
                    try {
                        sh '''
                            echo "=== 调试信息 ==="
                            echo "当前工作目录: $(pwd)"
                            echo "工作空间文件:"
                            ls -la || true
                            echo "Git 状态:"
                            git status || true
                            echo "Go 环境:"
                            export PATH=/usr/local/go/bin:$PATH
                            go version || true
                        '''
                    } catch (Exception e) {
                        echo "无法获取调试信息: ${e.getMessage()}"
                    }
                }
            }
        }
        
        cleanup {
            script {
                echo "清理工作空间..."
                // 可选：清理临时文件
                // sh 'rm -rf tmp/ || true'
            }
        }
    }
} 